package com.myfojing.mycloud;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;

import java.util.Locale;

import static android.content.Context.WIFI_SERVICE;

public class WiFiStateReceiver extends BroadcastReceiver {
    WiFiStateListener listener;

    public static String intToIp(int ip) {
        return String.format(Locale.ENGLISH, "%d.%d.%d.%d",
                (ip & 0xff),
                (ip >> 8 & 0xff),
                (ip >> 16 & 0xff),
                (ip >> 24 & 0xff));
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            // get ip
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
            DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
            String address = intToIp(dhcpInfo.ipAddress);
            if (listener != null) {
                listener.change_ip(address);
            }
        }
    }

    /* 自定义函数 */
    public void setListener(WiFiStateListener listener) {
        this.listener = listener;
    }

    interface WiFiStateListener {
        void change_ip(String address);
    }
    // end
}
